package com.itita.ww2.handler.requesthandler.account;

import java.sql.SQLException;
import java.util.Arrays;

import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.handler.IRequestData;
import com.itita.ww2.utils.handler.IRequestOper;
import com.smartfoxserver.v2.db.SFSDBManager;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSArray;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * 设置昵称
 * @author NorthLan
 *
 */
public class SetNickName implements IRequestOper, IRequestData {
	private SFSDBManager dbManager;

	@Override
	public void init(Object[] objs) {
		dbManager = (SFSDBManager) objs[0];
	}

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		String nickname = params.getUtfString("nickname");
		ISFSObject backObj = SFSObject.newInstance();
		backObj.putUtfString("nickname", nickname);
		// 
		//		String regex = "(?! )(?!.*? $)[^`~!@#\\$%\\^&\\*\\(\\)-=_\\+\\[\\]\\{\\}\\|;':\",\\./<>\\?]{2,16}";
		//		if (!Pattern.matches(regex, nickname)) {
		//			throw new WW2Exception(WW2ExceptionCode.INVALID_OPT, backObj);
		//		}
		// 不能重名
		{
			String sql = "SELECT * FROM `users` WHERE nickname = ?";
			ISFSArray arr = dbManager.executeQuery(sql, Arrays.asList(nickname).toArray());
			if (arr.size() > 0) {
				throw new WW2Exception(WW2ExceptionCode.NICKNAME_EXISTS, backObj);
			}
		}

		// 更新昵称
		{
			String sql = "UPDATE `users` SET `nickname` = ? WHERE id = ?";
			dbManager.executeUpdate(sql, Arrays.asList(nickname, userProfile.getUid()).toArray());
		}
		userProfile.setNickname(nickname);

		// 新手引导设置一下
		if (params.containsKey("guidestep")) {
			userProfile.getUserInfo().setGuideStep(params.getInt("guidestep"));
		}

		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}

}
